package com.kpijavatraining.module;

import java.io.Serializable;
import com.kpijavatraining.module.utils.Indexes;
import com.kpijavatraining.module.utils.WrapperList;
import com.kpijavatraining.module2.question.Question;

public class Session implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7702195854504135156L;
	private final int countOfQuestions;
	private int indexOfCurrentTopic;
	private int indexOfCurrentQuestion;
	private int numberOfQuestion;
	private int score;
	private int tempScore;	
	private WrapperList<Indexes> indexes = new WrapperList<>();
	private WrapperList<WrapperList<Question>> questions;
	private User user;
	
	public Session(WrapperList<WrapperList<Question>> list, User user) throws CloneNotSupportedException{
		questions = list;
		this.user = user;
		countOfQuestions = list.getCountOfElements();
	}
	
	public void answer(String results){
		questions.getElement(getIndexOfCurrentTopic()).getElement(getIndexOfCurrentQuestion()).answer(results);
		setScore();
		redo();
	}
	
	public int getNumberOfQuestion() {
		return numberOfQuestion;
	}
	
	public int getCountOfQuestions(){
		return countOfQuestions;
	}
			
	public int getScore(){
		return score;
	}

	public void prevQuestion(){
		if(numberOfQuestion > 0){
			undo();
            score -= questions.getElement(getIndexOfCurrentTopic()).getElement(getIndexOfCurrentQuestion()).getScore();
            tempScore = score;
            questions.getElement(getIndexOfCurrentTopic()).getElement(getIndexOfCurrentQuestion()).clear();
		}
	}
		
	public String toString(){
		return questions.getElement(getIndexOfCurrentTopic()).getElement(getIndexOfCurrentQuestion()).toString();
	}

	public User getUser() {
		return user;
	}
	
	private void redo(){
		indexes.add(new Indexes(getIndexOfCurrentTopic(),getIndexOfCurrentQuestion()));
		if(tempScore != score){
			if(indexOfCurrentTopic < getCountOfTopic()){
				indexOfCurrentTopic++;
			}else{
				indexOfCurrentTopic = 0;
				indexOfCurrentQuestion++;
			}
		}else{
			indexOfCurrentQuestion++;
		}
		tempScore = score;
		numberOfQuestion++;
	}
		
	private void undo(){
		questions.getElement(getIndexOfCurrentTopic()).getElement(getIndexOfCurrentQuestion()).setScore(0);
		indexOfCurrentTopic = indexes.getElement(numberOfQuestion - 1).getX();
		indexOfCurrentQuestion = indexes.getElement(numberOfQuestion - 1).getY();	
		indexes.delete(--numberOfQuestion);
	}
	
	private int getIndexOfCurrentQuestion(){
		return indexOfCurrentQuestion;
	}
	
	private void setScore() {
		score += questions.getElement(indexOfCurrentTopic).getElement(indexOfCurrentQuestion).getScore();	
	}
	
	private int getIndexOfCurrentTopic(){
		return indexOfCurrentTopic;
	}
	
	private int getCountOfTopic(){
		return questions.getCountOfElements();
	}
}
	